// distributor/pages/applyPerson/applyPerson.js
var common = require("../../../common/common.js").common;

var colorParse = require("../../../common/color.js");

var {$author: $author} = require("../../../components/base/authorization.js");

var app = getApp();

Page({
    /**
   * 页面的初始数据
   */
    data: {
        share: 0
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        this.setData({
            domain: app.globalData.domain.slice(0, -10)
        });
        wx.hideShareMenu();
        let that = this;
        wx.getSystemInfo({
            success: function(res) {
                let rpx = res.windowWidth / 375;
                that.setData({
                    rpx: rpx
                });
            }
        });
        //首次直接进入，拿user_id
                if (app.globalData.user) {
            //如果直接拿到openid
            this.setData({
                uid: app.globalData.user.uid,
                user: app.globalData.user
            });
            this.requestStart();
        } else {
            //回调拿到openid
            app.userInfoReadyCallback = (res => {
                this.setData({
                    uid: res.uid,
                    user: app.globalData.user
                });
                this.requestStart();
            });
        }
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {},
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {},
    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {},
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function() {
        this.requestStart();
        wx.stopPullDownRefresh();
    },
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {},
    /**
   * 用户点击右上角分享
   */
    onShareAppMessage: function() {
        let that = this;
        return {
            title: that.data.share_title,
            imageUrl: that.data.share_index,
            path: "/pages/index/index?uid=" + that.data.uid
        };
    },
    requestStart: function() {
        let that = this;
        that.getBase();
        that.getData();
    },
    getBase: function() {
        var that = this;
        common.request({
            endpoint: "set/app_base",
            data: {},
            success: res => {
                var copyText = [];
                if (res.extra.copyright_msg) {
                    var copy = res.extra.copyright_msg;
                    if (copy.indexOf(",") != -1) {
                        copyText = copy.split(",");
                    } else {
                        copyText[0] = copy;
                    }
                }
                var rgba = colorParse.hexToRgb(res.extra.color_main, .8);
                that.setData({
                    color_main: res.extra.color_main,
                    color_main2: rgba,
                    color_minor: res.extra.color_minor,
                    apptitle: res.extra.title,
                    style: res.extra.style,
                    leader_change: res.extra.l_change,
                    phone: res.extra.phone,
                    copyImg: res.extra.copyright_img,
                    copyText: copyText,
                    l_supply: res.extra.l_supply,
                    rp_name: res.extra.rp_name,
                    leaderName: res.extra.leader_title ? res.extra.leader_title : "团长",
                    leader_address_on: res.extra.leader_address_on,
                    vip_card_on: res.extra.vip_card_on,
                    share_title: res.extra.share_title ? res.extra.share_title : res.extra.title,
                    //首页分享标题
                    share_index: res.extra.share_index,
                    //首页分享图链接
                    new_member_audit: res.extra.new_member_audit,
                    userAuditStatus: res.extra.userAuditStatus ? res.extra.userAuditStatus : 2,
                    custom_title: res.extra.level_set.custom_title,
                    level_set: res.extra.level_set
                });
                //处理模块开关
                                var features = common.getModulesSwich(res.extra.features);
                //处理数据格式
                                that.setData({
                    features: features
                });
            }
        });
    },
    getQr: function() {
        var that = this;
        common.request({
            endpoint: "/Level/level/level-qr",
            method: "post",
            data: {
                page: "distributor/pages/applyDistributor/applyDistributor"
            },
            success: res => {
                let qr = res.extra.qr;
                if (qr.indexOf("https:") < 0) {
                    qr = qr.replace("http:", "https:");
                }
                let share_img = res.extra.share_img;
                if (share_img.indexOf("https:") < 0) {
                    share_img = share_img.replace("http:", "https:");
                }
                that.setData({
                    qr: qr,
                    share_img: share_img
                });
                that.showShareCode();
            }
        });
    },
    hideShareModal: function() {
        let that = this;
        that.setData({
            share: 0
        });
    },
    showShareModal: function() {
        let that = this;
        that.setData({
            share: 1
        });
    },
    getData: function() {
        var that = this;
        common.request({
            endpoint: "Level/level_user/general",
            method: "post",
            data: {
                user_id: that.data.uid
            },
            success: res => {
                that.setData({
                    details: res.extra
                });
                that.getQr();
            }
        });
    },
    gotoUrl: function(e) {
        let that = this;
        wx.navigateTo({
            url: e.currentTarget.dataset.url
        });
    },
    showShareCode: function() {
        let that = this;
        console.log("二维码？？？？");
        console.log(that.data.share_img);
        console.log(that.data.details.img);
        var avatar = that.data.details.img;
        if (avatar.indexOf("https:") < 0) {
            avatar = avatar.replace("http:", "https:");
        }
        const ctx = wx.createCanvasContext("share_box");
        wx.getImageInfo({
            src: that.data.share_img,
            success(res) {
                ctx.drawImage(res.path, 0, 0, 305 * that.data.rpx, 465 * that.data.rpx);
                ctx.drawImage(that.data.domain + "/img/mainPack/share_distrubte.png", 10 * that.data.rpx, 342 * that.data.rpx, 286 * that.data.rpx, 122 * that.data.rpx);
                wx.getImageInfo({
                    src: avatar,
                    success(res) {
                        ctx.save();
                        ctx.arc(37.5 * that.data.rpx, 387.5 * that.data.rpx, 17.5 * that.data.rpx, 0, 2 * Math.PI);
                        ctx.setFillStyle("#fff");
                        ctx.clip();
                        ctx.drawImage(res.path, 20 * that.data.rpx, 372 * that.data.rpx, 35 * that.data.rpx, 35 * that.data.rpx);
                        ctx.restore();
                        that.dealWords({
                            ctx: ctx,
                            font: "normal bold 12px sans-serif",
                            FillStyle: "#434343",
                            word: that.data.details.nickname,
                            maxWidth: 100 * that.data.rpx,
                            x: 70 * that.data.rpx,
                            y: 365 * that.data.rpx,
                            maxLine: 1
                        });
                        ctx.setFillStyle("#969696");
                        ctx.font = "9px Microsoft YaHei";
                        ctx.fillText("邀请与您一起分享赚钱", 70 * that.data.rpx, 400 * that.data.rpx);
                        ctx.setStrokeStyle("#969696");
                        ctx.rect(62.5 * that.data.rpx, 419 * that.data.rpx, 80 * that.data.rpx, 20 * that.data.rpx);
                        ctx.setFillStyle("#434343");
                        ctx.font = "10px Microsoft YaHei";
                        ctx.fillText("长按二维码识别", 70 * that.data.rpx, 432 * that.data.rpx);
                        ctx.stroke();
                        wx.getImageInfo({
                            src: that.data.qr,
                            success(res) {
                                ctx.drawImage(res.path, 180 * that.data.rpx, 360 * that.data.rpx, 98 * that.data.rpx, 98 * that.data.rpx);
                                ctx.draw(true, () => {
                                    var e = {
                                        currentTarget: {
                                            dataset: {
                                                type: "share"
                                            }
                                        }
                                    };
                                    that.dosave(e);
                                });
                            },
                            fail() {}
                        });
                    }
                });
            },
            fail() {},
            complete() {}
        });
    },
    saveimgdo: function(e) {
        var that = this;
        console.log(123);
        wx.getSetting({
            success(res) {
                if (!res.authSetting["scope.writePhotosAlbum"]) {
                    wx.authorize({
                        scope: "scope.writePhotosAlbum",
                        success() {
                            that.dosave(e);
                        },
                        fail() {
                            wx.openSetting();
                            wx.showModal({
                                title: "提示",
                                content: "未授权相册，请删小程序后再试！"
                            });
                        }
                    });
                } else {
                    that.dosave(e);
                }
            }
        });
    },
    dosave: function(e) {
        var that = this;
        wx.canvasToTempFilePath({
            x: 0,
            y: 0,
            width: 310 * that.data.rpx,
            height: 465 * that.data.rpx,
            canvasId: "share_box",
            success: function(res) {
                if (e.currentTarget.dataset.type == "share") {
                    var prevList = [];
                    prevList.push(res.tempFilePath);
                    that.setData({
                        prevList: prevList
                    });
                } else if (e.currentTarget.dataset.type == "save") {
                    wx.saveImageToPhotosAlbum({
                        filePath: res.tempFilePath,
                        success: function(res) {
                            wx.showModal({
                                title: "提醒",
                                content: "请转发您专属的分享图至好友",
                                showCancel: false,
                                success: function(res) {}
                            });
                        },
                        fail: function(res) {
                            console.log("fail");
                        }
                    });
                }
            }
        });
    },
    goToMyWallet: function(e) {
        let that = this;
        wx.navigateTo({
            url: e.currentTarget.dataset.url + encodeURIComponent(JSON.stringify(that.data.details))
        });
    },
    //处理文字多出省略号显示
    dealWords: function(options) {
        options.ctx.setFontSize(options.fontSize);
        //设置字体大小
                options.ctx.setFillStyle(options.FillStyle);
        //设置字体颜色
                var allRow = Math.ceil(options.ctx.measureText(options.word).width / options.maxWidth);
        //实际总共能分多少行
                var count = allRow >= options.maxLine ? options.maxLine : allRow;
        //实际能分多少行与设置的最大显示行数比，谁小就用谁做循环次数
                var endPos = 0;
        //当前字符串的截断点
                for (var j = 0; j < count; j++) {
            var nowStr = options.word.slice(endPos);
            //当前剩余的字符串
                        var rowWid = 0;
            //每一行当前宽度    
                        if (options.ctx.measureText(nowStr).width > options.maxWidth) {
                //如果当前的字符串宽度大于最大宽度，然后开始截取
                for (var m = 0; m < nowStr.length; m++) {
                    rowWid += options.ctx.measureText(nowStr[m]).width;
                    //当前字符串总宽度
                                        if (rowWid > options.maxWidth) {
                        if (j === options.maxLine - 1) {
                            //如果是最后一行
                            options.ctx.fillText(nowStr.slice(0, m - 1) + "...", options.x, options.y + (j + 1) * 18);
                            //(j+1)*18这是每一行的高度        
                                                } else {
                            options.ctx.fillText(nowStr.slice(0, m), options.x, options.y + (j + 1) * 18);
                        }
                        endPos += m;
                        //下次截断点
                                                break;
                    }
                }
            } else {
                //如果当前的字符串宽度小于最大宽度就直接输出
                options.ctx.fillText(nowStr.slice(0), options.x, options.y + (j + 1) * 18);
            }
        }
    }
});